package com.ujn.demo.use;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;

import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.*;
import com.ujn.demo.model.IDCardModel;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class IDCardOCR {

    private static final Logger LOGGER = LoggerFactory.getLogger(IDCardOCR.class);

    private static final String secretId = "AKIDDHGsQm09ICttf6bfOvIUUJQLCHk6qwlP";

    private static final String secretKy = "lIgstkNWSVOF9rPmx5MVuGdr0uaSA0fD";

    private static final String basePath = "C:\\Users\\可爱的小宝贝\\Desktop\\身份证\\0319\\第一批\\test";


    public static void main(String [] args) throws IOException {

        List<IDCardModel> idCardModels = useOcrApi();

        writeIdCardExcel(idCardModels);
    }

    /**
     * 写excel
     * @throws IOException
     */
    public static void writeIdCardExcel(List<IDCardModel> idCardlList) throws IOException {
        try{
            // 创建工作薄
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 创建工作表
            HSSFSheet sheet = workbook.createSheet("sheet1");

            //设置标头
            HSSFRow zeroRows = sheet.createRow(0);
            zeroRows.createCell(0).setCellValue("姓名");
            zeroRows.createCell(1).setCellValue("性别");
            zeroRows.createCell(2).setCellValue("民族");
            zeroRows.createCell(3).setCellValue("出生日期");
            zeroRows.createCell(4).setCellValue("住址");
            zeroRows.createCell(5).setCellValue("身份证号码");

            //row 行数
            for (int row = 1; row <= idCardlList.size(); row++) {
                HSSFRow rows = sheet.createRow(row);
                //clo 列数
                for (int col = 0; col < 6; col++) {
                    if (col == 0){
                        rows.createCell(col).setCellValue(idCardlList.get(row-1).getName());
                    }else if (col == 1){
                        rows.createCell(col).setCellValue(idCardlList.get(row-1).getSex());
                    }else if (col == 2){
                        rows.createCell(col).setCellValue(idCardlList.get(row-1).getNation() + "族");
                    }else if (col == 3){
                        rows.createCell(col).setCellValue(idCardlList.get(row-1).getBirth().replaceAll("/", "-"));
                    }else if (col == 4){
                        rows.createCell(col).setCellValue(idCardlList.get(row-1).getAddress());
                    }else if (col == 5){
                        rows.createCell(col).setCellValue(idCardlList.get(row-1).getIdNum());
                    }
                }
            }
            String time = "/身份证复印件转文字-" + getTime() + ".xls";
            File xlsFile = new File(basePath + time);
            xlsFile.createNewFile();
            FileOutputStream xlsStream = new FileOutputStream(xlsFile);
            workbook.write(xlsStream);
            LOGGER.info("身份证复印件转文字成功。请查看excel位置：{}", xlsFile.getAbsolutePath());
        }catch (Exception e){
            LOGGER.error("转化excel失败:{}", e);
        }

    }

    /**
     * 获取时间
     * @return
     */
    public static String getTime(){
        Date currentTime = new Date();
        //改变输出格式（自己想要的格式）
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
        //得到字符串时间
        String time = formatter.format(currentTime);
        return time;
    }

    /**
     * 调用ocr Api方法
     * @return
     */
    public static List<IDCardModel> useOcrApi(){
        //遍历图片数组
        List<String> picList = new ArrayList<String>();
        File file = new File(basePath);
        if (file.isFile() || !file.exists()) {
            LOGGER.error("basePath目录有误！");
        }
        File[] files = file.listFiles();
        for (File fl:files){
            if (fl.isFile() && (fl.getName().contains("jpg") || fl.getName().contains("png") || fl.getName().contains("jpeg"))){
                picList.add(fl.getAbsolutePath());
            }
        }

        //循环调用解析腾讯云ocr接口
        List<String> ocrList = new ArrayList<>();
        List<IDCardModel> list = new ArrayList<>();
        for (String str:picList){
            String imgBase64 = getImgStr(str);
            String picToWord = picToWord(imgBase64, str);
            if (!StringUtils.isEmpty(picToWord)){
                ocrList.add(picToWord);
                IDCardModel idCardModel = JSONObject.parseObject(picToWord, IDCardModel.class);
                list.add(idCardModel);
            }
            System.out.println(picToWord);
        }
        LOGGER.debug("useOcrApi, list:{}", JSON.toJSON(list));
        return list;
    }

    /**
     * 图片转base64编码
     * @param imgFile
     * @return
     */
    public static String getImgStr(String imgFile){
            //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
            InputStream in = null;
            byte[] data = null;
            //读取图片字节数组
            try {
                 in = new FileInputStream(imgFile);
                 data = new byte[in.available()];
                 in.read(data);
                 in.close();
            } catch (IOException e) {
                 e.printStackTrace();
            }
            return new String(Base64.encodeBase64(data));
    }


    /**
     * 身份证图片转化为文字
     * @param base64Str
     * @return
     */
    public static String picToWord(String base64Str, String pictureStr){
        String response = "";
        try{
            Credential cred = new Credential(secretId, secretKy);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            OcrClient client = new OcrClient(cred, "ap-guangzhou", clientProfile);

            IDCardOCRRequest req = new IDCardOCRRequest();

            //图片的base64编码
            req.setImageBase64(base64Str);
            //FRONT：身份证有照片的一面（人像面），
            //BACK：身份证有国徽的一面（国徽面），
            //该参数如果不填，将为您自动判断身份证正反面。
            req.setCardSide("FRONT");

            IDCardOCRResponse resp = client.IDCardOCR(req);
            response = IDCardOCRResponse.toJsonString(resp);
            LOGGER.info("picToWord, response:{}", response);
        } catch (TencentCloudSDKException e) {
            LOGGER.error("picToWord, response:{},失败图片路径：{}", e.toString(), pictureStr);
        }
        return response;
    }
}
